package drds.global_transaction.resource_manager.model;

import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class TableMetaData
{
	@Setter
	@Getter
	private String tableName;
	@Setter
	@Getter
	private Map<String, ColumnMetaData> columnNameToColumnMetaDataMap = new HashMap<String, ColumnMetaData>();
	@Setter
	@Getter
	private Map<String, IndexMetaData> columnNameToIndexMetaDataMap = new HashMap<String, IndexMetaData>();

	public boolean containsAllPrimaryKeyColumnNameList(List<String> columnNameList)
	{
		if (columnNameList == null)
		{
			return false;
		}

		List<String> primaryKeyColumnNameList = getPrimaryKeyColumnNameList();
		if (primaryKeyColumnNameList.isEmpty())
		{
			return false;
		}
		return columnNameList.containsAll(primaryKeyColumnNameList);
	}

	public ColumnMetaData getColumnMeta(String columnName)
	{
		columnName = columnName.toLowerCase();
		ColumnMetaData columnMetaData = columnNameToColumnMetaDataMap.get(columnName);
		if (columnMetaData == null)
		{
			if (columnName.charAt(0) == '`')
			{
				columnMetaData = columnNameToColumnMetaDataMap.get(columnName.substring(1, columnName.length() - 1));
			} else
			{
				columnMetaData = columnNameToColumnMetaDataMap.get("`" + columnName + "`");
			}
		}
		return columnMetaData;
	}

	public String getFirstPrimaryKeyColumnName()
	{
		return getPrimaryKeyColumnNameList().get(0);
	}

	@SuppressWarnings("serial")
	public List<String> getPrimaryKeyColumnNameList()
	{
		return new ArrayList<String>()
		{
			{
				for (Entry<String, ColumnMetaData> entry : getPrimaryKeyColumnNameToColumnMetaDataHashMap().entrySet())
				{
					add(entry.getKey());
				}
			}
		};
	}

	public Map<String, ColumnMetaData> getPrimaryKeyColumnNameToColumnMetaDataHashMap()
	{
		Map<String, ColumnMetaData> columnNameToColumnMetaDataHashMap = new HashMap<String, ColumnMetaData>();
		for (Entry<String, IndexMetaData> entry : columnNameToIndexMetaDataMap.entrySet())
		{
			IndexMetaData indexMetaData = entry.getValue();
			if (indexMetaData.getIndextype().value() == IndexType.primary_key.value())
			{
				for (ColumnMetaData columnMetaData : indexMetaData.getColumnMetaDataList())
				{
					columnNameToColumnMetaDataHashMap.put(columnMetaData.getColumnName().toLowerCase(), columnMetaData);
				}
			}
		}

		if (columnNameToColumnMetaDataHashMap.size() > 1)
		{
			throw new IllegalStateException("只支持一个主键");
		}
		return columnNameToColumnMetaDataHashMap;
	}
}
